<!-- JsonTree.vue -->
<template>
	<div class="json-tree">
		<div v-if="isNoData" class="h-[300px] flex items-center justify-center">暂无可选数据</div>

		<template v-else>
			<json-tree-node
				:node-data="processedData"
				:parent-path="parentPath"
				:selected-path="selectedPath"
				@node-selected="handleNodeSelected"
			/>
		</template>
	</div>
</template>

<script setup>
	import { computed, ref, watch } from 'vue'
	import JsonTreeNode from './JsonTreeNode.vue'
	import { designStore } from '@/views/plugin/dashboard/store'
	const useDesignStore = designStore()

	const props = defineProps({
		// 原始数据（接受任意JSON结构）
		data: {
			type: [Object, Array],
			default: () => ({})
		},
		// 初始选中路径
		modelValue: {
			type: String,
			default: ''
		},
		// 初始选中的接口
		apiId: {
			type: String,
			default: ''
		}
	})

	const defaultData = ref({})

	const emit = defineEmits(['update:modelValue', 'selected'])
	const proData = computed(() => {
		const data = { ...defaultData.value, ...props.data }
		return { [data.name]: data }
	})

	const isNoData = computed(() => {
		return !Object.entries(defaultData.value).length && !Object.entries(props.data).length
	})

	// 处理数组数据转换为带索引的对象
	const processedData = computed(() => {
		if (Array.isArray(proData.value)) {
			return Object.fromEntries(proData.value.map((item, index) => [index, item]))
		}
		return proData.value
	})

	// 当前选中路径
	const selectedPath = ref('')
	const parentPath = ref('')

	// 初始默认
	watch(
		() => props.apiId,
		(newVal) => {
			// 如果有选值
			if (newVal) {
				useDesignStore.dataSource.forEach((parent) => {
					parent.config.indicators.forEach((child) => {
						if (child.id === newVal) {
							defaultData.value = child
						}
					})
				})
			}
		},
		{ immediate: true } // 立即执行一次
	)
	// 路径处理观察器
	watch(
		() => props.modelValue,
		(newVal) => {
			// 如果传入的是非一级路径，需要添加一级路径前缀
			if (newVal) {
				const rootKey = Object.keys(processedData.value)[0]
				selectedPath.value = newVal.includes('.') ? `${rootKey}.${newVal}` : `${rootKey}.${newVal}`
			} else {
				selectedPath.value = newVal
			}
		},
		{ immediate: true } // 立即执行一次
	)

	// 节点选中事件处理
	const handleNodeSelected = ({ path, value }) => {
		// 移除一级路径
		const processedPath = path.includes('.') ? path.split('.').slice(1).join('.') : ''
		selectedPath.value = path // 保持完整路径用于内部选中状态
		emit('update:modelValue', processedPath) // 向外部发送不含一级路径的值
		emit('selected', { path: processedPath, value })
	}

	// 路径解析工具方法
	const getValueFromPath = (path) => {
		try {
			// 添加一级节点名称回去
			const fullPath = Object.keys(processedData.value)[0] + '.' + path
			return fullPath.split('.').reduce((acc, key) => {
				// 处理数组索引的方括号格式
				const arrayMatch = key.match(/\[(\d+)\]$/)
				if (arrayMatch) {
					const arrayKey = arrayMatch[1]
					const parentKey = key.replace(/\[\d+\]$/, '')
					return acc[parentKey][arrayKey]
				}
				return acc[key]
			}, processedData.value)
		} catch {
			return undefined
		}
	}
</script>

<style scoped>
	.json-tree {
		--tree-indent: 10px;
		--primary-color: #2196f3;
		--text-color: #333;
		font-family: 'Menlo', 'Consolas', monospace;
		padding: 8px;
		border: 1px solid #eee;
		border-radius: 2px;
		background: white;
	}
</style>
